import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import React, { useState, useEffect, FC } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";

interface Props {
  value: String
  onChange: (value: String) => void
}

const Title: React.FC<Props> = ({
  value,
  onChange,
}) => {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 编辑器内容
  const [text, setText] = useState(value ? value : '')
  const [html, setHtml] = useState(`<p>${text}</p>`);
  //

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {

  }, []);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: "请输入内容...",
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  const handleChange = (editor: any) => {
    const text = editor.getText()
    onChange(text)
  };
  return (
    <>
      <div style={{ border: "1px solid #ccc", zIndex: 100, marginTop: "30px", width: "800px" }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: "1px solid #ccc" }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={handleChange}
          mode="default"
          style={{ width: "800px", height: "200px", overflowY: "hidden", }}
        />
      </div>
      <div style={{ marginTop: "15px" }}></div>
    </>
  );
}

export default Title;
